<template>
  <a-tooltip
    :visible="visible"
    :mouse-enter-delay="200"
    :mouse-leave-delay="1000"
    placement="top"
  >
    <template v-if="show" slot="title">
      <span v-if="show">{{ text | format(formatter) }}</span>
    </template>
    <div
      class="div-tool"
      style="display: inline-block; position: relative; width: 100%"
    >
      <span
        ref="text"
        :style="{
          cursor: typeof setColor === 'string' ? 'pointer' : '',
          color: setColor
        }"
        :class="['ellipsis', typeof setColor === 'string' ? 'buttonlink' : '']"
        @click="opertor(setColor)"
        @mouseleave="triggerLeave(false)"
        @mousemove="triggerRef"
      >
        &nbsp;
        {{ text | format(formatter) }}
      </span>
    </div>
  </a-tooltip>
</template>
<script>
import debounce from 'lodash.debounce'
export default {
  filters: {
    format(text, obj) {
      //
      return obj ? obj[text] : text
    }
  },
  props: {
    badgeStatusList: {
      type: Array,
      default: () => []
    },
    setColor: {
      type: [Function, String],
      default: () => {
        return () => {
          return ''
        }
      }
    },
    text: {
      type: [String, Number],
      default: ''
    },
    formatter: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return { show: false, visible: false, time: null }
  },
  watch: {
    text() {
      this.$nextTick(() => {
        this.show = this.$refs.text
          ? this.$refs.text.scrollWidth > this.$refs.text.offsetWidth
          : false
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.show = this.$refs.text
        ? this.$refs.text.scrollWidth > this.$refs.text.offsetWidth
        : false
    })
  },
  methods: {
    triggerLeave(v) {
      if (this.time) {
        window.clearTimeout(this.time)
      }
      setTimeout(() => {
        this.visible = false
      }, 2000)
    },
    triggerRef: debounce(function () {
      // 优化鼠标移入事件
      this.visible =
        this.visible ||
        this.$refs.text.scrollWidth > this.$refs.text.offsetWidth
    }, 200),
    opertor(setColor) {
      this.$emit('setEvent')
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  width: 100%;
  position: absolute;
  left: 0;
  right: 0;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  color: #606266;
  display: inline-block;
}
.div-tool {
  display: inline-block;
  position: relative;
  width: 100%;
  &::before {
    content: '*';
    opacity: 0;
  }
}
</style>
